﻿//#define NO_TESSELLATE

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
using Box2DX.Common;
using Box2DX.Collision;
using Box2DX.Dynamics;

#if !SILVERLIGHT
using Tessellation;
#endif

namespace Expression.Samples.Physics
{
	public static class ShapeHelper
	{
		
		public static void CreateShapesFromElement(Simulator simulator, Body body, BodyParameters bodyParameters, Entity entity) {
			List<ShapeDef> shapeDefs = new List<ShapeDef>();

			if (entity.Shape is Ellipse) {
				CircleDef circleDef = new CircleDef();


				Vector2 worldRadius = simulator.SimulatorContext.ScreenSizeToWorldSize(new Size(entity.Shape.ActualWidth, entity.Shape.ActualHeight).Div(2));

				circleDef.Radius = worldRadius.Y;
				shapeDefs.Add(circleDef);
			}
			else if (entity.Shape is Rectangle) {

				PolygonDef polygonDef = new PolygonDef();
				Rectangle rectangle = entity.Shape as Rectangle;

				Rect rect = new Rect(0, 0, rectangle.ActualWidth, rectangle.ActualHeight);
				Vector2 worldSize = simulator.SimulatorContext.ScreenSizeToWorldSize(new Size(rect.Width, rect.Height).Div(2));
				polygonDef.SetAsBox(worldSize.X, worldSize.Y);
				shapeDefs.Add(polygonDef);
			}
			else if (entity.Shape is IShapeGeometry) {
				ShapeDef shapeDef = ((IShapeGeometry)entity.Shape).GetShapeDefinition(simulator.SimulatorContext);
				shapeDefs.Add(shapeDef);
			}
			else
			{
				Vector2 size = simulator.SimulatorContext.ScreenSizeToWorldSize(entity.ElementSize.Mul(0.5));
				PolygonDef polygonDef = new PolygonDef();

				bodyParameters.SetParameters(polygonDef);

				polygonDef.SetAsBox(size.X, size.Y);
				shapeDefs.Add(polygonDef);
			}

			foreach (ShapeDef shapeDef in shapeDefs) {
				bodyParameters.SetParameters(shapeDef);
				body.CreateShape(shapeDef);
			}
		}
	}
}
